Page({
  data: {
    mode: 'add',             // 模式：'add' 或 'edit'
    id: '',                  // 编辑时的文档ID
    question: '',            // 问题内容
    types: ['单选', '填空','地址','滑动条'],  // 支持的题型
    typeIndex: 0,            // 默认选择“单选”
    options: [],         // 单选题的选项列表（数组形式）
    sliderMin: '',            // 滑动条题型的最小值
    sliderMax: ''             // 滑动条题型的最大值
  },
  onLoad: function (options) {
    // 获取传入参数
    this.setData({ mode: options.mode });
    if (options.mode === 'edit' && options.id) {
      this.setData({ id: options.id });
      // 加载指定问题数据
      const db = wx.cloud.database();
      db.collection('question_daily').doc(options.id).get().then(res => {
        const data = res.data;
        let typeIndex = 0;
        if (data.type === 'radio') {
          typeIndex = 0;
        } else if (data.type === 'input') {
          typeIndex = 1;
        } else if (data.type === 'address') {
          typeIndex = 2;
        } else if (data.type === 'slider') {
          typeIndex = 3;
        }
        this.setData({
          question: data.question,
          typeIndex: typeIndex,
          options: data.options ? data.options : [],
          sliderMin: data.sliderMin !== undefined ? data.sliderMin : '',
          sliderMax: data.sliderMax !== undefined ? data.sliderMax : ''
        });
      }).catch(err => {
        console.error(err);
      });
    }
  },
  // 题型选择变更
  bindTypeChange: function (e) {
    let newTypeIndex = e.detail.value;
    this.setData({ typeIndex: newTypeIndex });
  },
  // 处理选项输入
  onOptionInput: function (e) {
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    let options = this.data.options;
    options[index] = value;
    this.setData({ options });
  },
  // 新增选项（追加一个空字符串）
  addOption: function () {
    let options = this.data.options;
    options.push("");
    this.setData({ options });
  },
  // 删除某个选项
  deleteOption: function (e) {
    let index = e.currentTarget.dataset.index;
    let options = this.data.options;
    options.splice(index, 1);
    this.setData({ options });
  },
  // 上移选项：与前一个选项交换位置
  moveOptionUp: function (e) {
    let index = parseInt(e.currentTarget.dataset.index);
    if (index <= 0) return;
    let options = this.data.options;
    [options[index - 1], options[index]] = [options[index], options[index - 1]];
    this.setData({ options });
  },
  // 下移选项：与后一个选项交换位置
  moveOptionDown: function (e) {
    let index = parseInt(e.currentTarget.dataset.index);
    let options = this.data.options;
    if (index >= options.length - 1) return;
    [options[index + 1], options[index]] = [options[index], options[index + 1]];
    this.setData({ options });
  },
  // 表单提交，保存或更新问题数据
  formSubmit: function (e) {
    const formData = e.detail.value;
    const questionContent = formData.question;
    const dbData={
      question: questionContent,
    };
    let typeStr = this.data.types[this.data.typeIndex];
    let type;
    if (typeStr === '单选') {
      type = 'radio';
    } else if (typeStr === '填空') {
      type = 'input';
    } else if (typeStr === '地址') {
      type = 'address';
    } else if (typeStr === '滑动条') {
      type = 'slider';
    }
    let optionsArr = [];
    if (type === 'radio') {
      // 过滤掉空字符串
      optionsArr = this.data.options.filter(item => item.trim() !== "");
    }
    else if (type === 'slider') {
      // 滑动条题型：获取最小值和最大值，并确保为整数
      let min = parseInt(formData.min);
      let max = parseInt(formData.max);
      if (isNaN(min) || isNaN(max)) {
        wx.showToast({ title: '请输入有效整数', icon: 'none' });
        return;
      }
      if (min >= max) {
        wx.showToast({ title: '最小值必须小于最大值', icon: 'none' });
        return;
      }
      dbData.sliderMin = min;
      dbData.sliderMax = max;
    }
    dbData.type=type;
    dbData.options=optionsArr;
    const db = wx.cloud.database();
    if (this.data.mode === 'add') {
      dbData.createdAt=new Date();
      dbData.order=Date.now();
      db.collection('question_daily').add({
        data: dbData,
      }).then(res => {
        
        wx.navigateBack();
        wx.showToast({ title: '添加成功' });
      }).catch(err => {
        console.error(err);
      });
    } else if (this.data.mode === 'edit') {
      dbData.updatedAt=new Date();
      console.log(this.data);
      db.collection('question_daily').doc(this.data.id).update({
        data: dbData
      }).then(res => {
        
        wx.navigateBack();
        wx.showToast({ title: '更新成功' });
      }).catch(err => {
        console.error(err);
      });
    }
  }
});
